const { Admin } = require("../models/adminModel");
const { Sales } = require("../models/salesModel");
//插件
//解密 加密
const { getEncAse128, setDecAse128 } = require('../utils/crypto')

const jwt = require('jsonwebtoken')

const {
    TOKEN_KEY
} = require('../utils/const');

// const { addItem } = require('./insureProductCon');

// async function register(req, res) {
//     const { username, password } = req.body

//     const userAlreadyExists = await Admin.find({ username })
//     if (userAlreadyExists.length > 0) {
//         res.send({
//             msg: "用户名已经存在",
//             status: 0
//         })
//     } else {
//         const newPassword = getEncAse128(password,'9vApxLk5G3PAsJrM');
//         // const newPassword=getMd5(password)

//         const data = await Admin.create({ username, password: newPassword });
//         res.send({
//             msg: "register success",
//             status: 1
//         })
//     }

// }
// 新增管理员
async function addAdmin(req, res) {
    const { username, password, permission } = req.body

    const data = await Admin.find({ username });


    if (data.length > 0) {
        res.send({
            status: 0,
            msg: "新增失败，用户名已经存在",

        })

    } else {

        const newPassword = getEncAse128(password, '9vApxLk5G3PAsJrM');
        const data = await Admin.create({ username, password: newPassword, permission });
        res.send({
            status: 1,
            msg: '新增成功'
        })
    }

}
//登录
async function login(req, res) {

    const { username, password, value } = req.body;

    if (value == "1") {
        const data = await Admin.find({ username });

        if (data.length > 0) {
            const newPassword = data[0].password;
            const permission = data[0].permission;

            const _id = data[0]._id;
            const isSame = setDecAse128(newPassword, '9vApxLk5G3PAsJrM')

            if (isSame) {

                const token = jwt.sign(
                    { _id, username, permission },
                    TOKEN_KEY,
                    { expiresIn: 60 * 60 }
                )
                res.send({
                    status: 1,
                    token,
                    msg: "login success",
                    value: "1"
                })

            }


        } else {
            res.send({
                msg: "login failed",
                status: 0
            })
        }
    } else {

        const Sdata = await Sales.find({ username });

        console.log(Sdata);
        if (Sdata.length > 0) {
            const newPassword = Sdata[0].password;
            const permission = Sdata[0].permission;

            console.log(permission);
            const _id = Sdata[0]._id;
            const isSame = setDecAse128(newPassword, '9vApxLk5G3PAsJrM')

            if (isSame) {

                const token = jwt.sign(
                    { _id, username, permission },
                    TOKEN_KEY,
                    { expiresIn: 60 * 60 }
                )
                res.send({
                    status: 1,
                    token,
                    msg: "login success",
                    status: 1,
                })

            }


        } else {
            res.send({
                msg: "login failed",
                status: 0
            })
        }
    }
    const data = await Admin.find({ username });
    const Sdata = await Sales.find({ username });
    if (data.length > 0) {
        const newPassword = data[0].password;
        const permission = data[0].permission;

        const _id = data[0]._id;
        const isSame = setDecAse128(newPassword, '9vApxLk5G3PAsJrM')

        if (isSame) {

            const token = jwt.sign(
                { _id, username, permission },
                TOKEN_KEY,
                { expiresIn: 60 * 60 }
            )
            res.send({
                status: 1,
                token,
                msg: "login success",
                status: 1,
            })

        }


    } else {
        res.send({
            msg: "login failed",
            status: 0
        })
    }


}
//查看管理员
async function getAllAdmins(req, res) {



    const { serachData, currentPage, pageSize } = req.body;
    const total = await Admin.countDocuments();

    const totalPages = Math.ceil(total / pageSize);
    let data = await Admin
        .find({ [serachData.type]: { $regex: serachData.value, $options: '$i' } })
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
    console.log(data);
    for (item of data) {
        item.password = setDecAse128(item.password, '9vApxLk5G3PAsJrM')
    }

    res.send({
        status: 1,
        data: { total, totalPages, data, pageSize, currentPage },
        msg: "数据获取成功"
    })
}
//修改权限
async function changeAdminAccess(req, res, next) {
    const { _id, permission } = req.body


    const result = await Admin.updateOne({ _id }, { permission })
    res.send({
        msg: "change admin status success",

        status: 0,
    })
}
//删除
async function deleteAdminByID(req, res) {
    const { _id } = req.body

    const data = await Admin.findByIdAndDelete(_id);
    if (data) {
        res.send({
            status: 1,
            message: '删除成功'
        })
    } else {
        res.send({
            status: 0,
            message: '删除失败'
        })
    }


}
//islogin
async function isLogin(req, res) {

    const auth = req.get('Authorization');

    const token = auth.split(' ')[1];
    const { username, permission, _id } = jwt.verify(token, TOKEN_KEY);

    res.send({
        status: 1,
        msg: '用户已登录',
        data: {
            _id,
            username,
            permission
        }
    })
}
//根据id获得管理员信息
async function getAdminById(req, res) {
    const { _id } = req.body;
    const data = await Admin.find({ _id })
    data[0].password = setDecAse128(data[0].password, '9vApxLk5G3PAsJrM')
    res.send({
        status: 1,
        msg: '获取成功',
        data,
    })

}
//update
async function updateAdmin(req, res) {
    const { _id, username, password, permission } = req.body;
    const newPassword = getEncAse128(password, '9vApxLk5G3PAsJrM')
    const data = await Admin.updateOne({ _id }, { username, password: newPassword, permission })

    res.send({
        status: 1,
        msg: '修改成功',

    })


}
module.exports = { addAdmin, login, getAllAdmins, deleteAdminByID, getAdminById, updateAdmin, isLogin }